﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace FormatUtil
{
    public  class FixedTimeTask
    {
      
        public delegate void DoWorkDelege();
        public event DoWorkDelege DoWork;

        private double _hours = 1.0;
        private double _minute = 0;
        public FixedTimeTask(double hours, double minute)
        {
            _hours = hours;
            _minute = minute;
            SetTaskAtFixedTime();
        }
        private void SetTaskAtFixedTime()
        {
            DateTime now = DateTime.Now;
            DateTime oneOClock = DateTime.Today.AddHours(_hours).AddMinutes(_minute);
            if (now > oneOClock)
            {
                oneOClock = oneOClock.AddDays(1.0);
            }
            int msUntilFour = (int)((oneOClock - now).TotalMilliseconds);

            var t = new System.Threading.Timer(DoAt1AM);
            t.Change(msUntilFour, Timeout.Infinite);
        }

        //要执行的任务
        private  void DoAt1AM(object state)
        {
            //执行功能...
            DoWork?.Invoke();
            //再次设定
            SetTaskAtFixedTime();
        }
    }
}
